let { userList, houseData, carData, h5UserList } = require('./mock')
const bodyParser = require('body-parser')
const jwt = require('jsonwebtoken')

// jwt 生成登录必要的签名，用来验证登录人信息

let authNum = 0

module.exports = {
    devServer: {
        before: app => {
            app.use(bodyParser.json())
            // 获取验证码
            app.post('/api/getAuthCode', (req, res) => {
                // 随机数
                authNum = Math.floor(Math.random() * (9999 - 1000 + 1) + 1000)

                res.send({
                    code: 0,
                    data: authNum
                })
            })

            // 登录
            app.post('/api/login', (req, res) => {
                // 获取由前端传来的数据
                const {
                    username,
                    password,
                    authCode
                } = req.body

                if (authNum !== authCode) {
                    res.send({
                        code: 1,
                        msg: '验证码错误'
                    })
                } else if (userList.some(item => item.username === username && item.password === password)) {
                    // 登录人名称
                    const name = userList.find(item => item.username === username && item.password === password).name

                    // jwt.sign(name, '1906A')   sign对数据进行加密，第一个参数是被加密的数据，第二个参数是加密规则（钥匙🔑）
                    const num = jwt.sign(name, '1906A')

                    res.send({
                        code: 0,
                        msg: '登录成功',
                        data: num
                    })
                } else {
                    res.send({
                        code: 1,
                        msg: "账号或者密码错误"
                    })
                }
            })

            // 获取用户信息
            app.post('/api/getUserInfo', (req, res) => {
                // 获取token
                const { authorization } = req.headers

                // 解密token  jwt.verify()  verify数据解密，第一个参数被解密的数据，第二个参数 解密的规则（钥匙）
                const name = jwt.verify(authorization, "1906A")

                // 用户信息
                const userInfo = { ...userList.find(item => item.name === name) }

                // 删除用户信息中的密码  delete 删除对象中的某个属性
                delete userInfo.password

                res.send({
                    code: 0,
                    data: userInfo
                })
            })

            // 角色
            app.post('/api/getRoleList', (req, res) => {
                res.send({
                    code: 0,
                    data: userList
                })
            })

            // 房源数据
            app.post('/api/getHouseList', (req, res) => {
                // size:每页条数  current：页码
                let { size, current, name, area, price, status } = req.body

                // 总总条数
                let total = 0

                let list = houseData

                // 通过条件筛选
                if (price) {
                    price = price * 1
                }

                if (name) {
                    list = list.filter(item => item.name.includes(name))
                }

                if (area) {
                    list = list.filter(item => item.area.includes(area))
                }

                if (price) {
                    list = list.filter(item => item.price === price)
                }

                if (status !== undefined) {
                    list = list.filter(item => item.status === status)
                }

                // 过滤后的数据总条数
                total = list.length

                // 通过条件筛选之后做分页器
                list = list.filter((item, idx) => {
                    return (current - 1) * size <= idx && idx <= current * size - 1
                })


                res.send({
                    code: 0,
                    data: {
                        list: list,
                        // 总条数
                        total
                    }
                })
            })

            // 删除数据
            app.post('/api/delete', (req, res) => {
                // 获取id
                const { id } = req.body

                houseData = houseData.filter(item => item.id !== id)

                res.send({
                    code: 0,
                    msg: '删除成功'
                })
            })

            // 编辑数据
            app.post('/api/editItem', (req, res) => {
                houseData = houseData.map(item => {
                    if (item.id === req.body.id) {
                        return {
                            ...req.body
                        }
                    } else return item
                })

                res.send({
                    code: 0,
                    msg: '修改成功'
                })
            })

            // 添加
            app.post('/api/addItem', (req, res) => {
                // 新数据添加id
                const newItem = {
                    ...req.body,
                    id: new Date().toDateString()
                }

                // 将新数据添加到数组第一个
                houseData.unshift(newItem)

                res.send({
                    code: 0,
                    msg: '添加成功'
                })

            })

            // 车的详情
            app.post('/api/carDetail', (req, res) => {
                res.send({
                    code: 0,
                    data: carData
                })
            })

            app.post('/api/getList', (req, res) => {
                res.send({
                    code:0,
                    msg: '连接成功'
                })
            })

            // =================手机端接口====================
            app.post('/api/h5/login', (req, res) => {
                const { code, username } = req.body
                if (code * 1 === authNum * 1 && h5UserList.some(item => item.username === username)) {
                    res.send({
                        code: 0,
                        token: jwt.sign(username, 'h5')
                    })
                } else {
                    res.send({
                        code: 1,
                        msg: '验证码或者手机号错误'
                    })
                }
            })

            app.post('/api/h5/getUserInfo', ((req, res) => {
                const { authorization } = req.headers

                // 解密token
                const username = jwt.verify(authorization, 'h5')

                const userInfo = h5UserList.find(item => item.username === username)

                res.send({
                    code: 0,
                    data: userInfo
                })
            }))
        }
    }
}